package com.hk.Mgr.web.controller.pay;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.jpush.api.JPushClient;
import cn.jpush.api.common.resp.APIConnectionException;
import cn.jpush.api.common.resp.APIRequestException;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.PushPayload.Builder;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.audience.AudienceTarget;
import cn.jpush.api.push.model.notification.Notification;

import com.hk.Mgr.web.message.customer.EqptReq;
import com.hk.base.BaseCtrl;
import com.hk.commons.DateUtil;
import com.hk.commons.StringHelper;
import com.hk.commons.entity.Eqpt;
import com.hk.service.kyc.IEqpt;

@Controller
public class aa {
	private static Logger logger = LoggerFactory.getLogger(aa.class);
	@Value("${jiguang.apiKey}")
	private String apiKey;

	@Value("${jiguang.masterSecret}")
	private String masterSecret;
	
	/**
	 * 极光推送
	 * 
	 * @param msg
	 * @param alias
	 * @param platForm
	 * @param tag
	 * @param registId
	 * @throws IOException
	 */
	// /common/jgPushCtr/sendMsg
	@ResponseBody
	@RequestMapping(value = "/aa", method = RequestMethod.GET)
	public void jgPushMsg(@RequestParam String msg,
			String platForm,
			String aliases, String tags, String registIds,
			HttpServletResponse response) throws IOException {
		logger.info("极光推送msg={},platForm={},aliases={},tags={},registIds={}",
				msg, platForm, aliases, tags, registIds);

		JPushClient jpushClient = new JPushClient(masterSecret, apiKey);
		PushPayload payload = buildPushObject_alert(msg, platForm, aliases,
				tags, registIds);
		try {
			PushResult result = jpushClient.sendPush(payload);
			logger.info("Got result - " + result);
			response.setCharacterEncoding("utf-8");
			response.getWriter().write("{\"success\":true }");
			response.getWriter().flush();
		} catch (APIConnectionException e) {
			logger.error("Connection error, should retry later", e);

		} catch (APIRequestException e) {
			logger.error("Should review the error, and fix the request", e);
			logger.info("HTTP Status: " + e.getStatus());
			logger.info("Error Code: " + e.getErrorCode());
			logger.info("Error Message: " + e.getErrorMessage());
		}
	}

	// 所有平台，推送目标是别名为 "alias1"，通知内容为 ALERT。
	public PushPayload buildPushObject_alert(String ALERT, String platForm,
			String aliases, String tags, String registIds) {
		Builder builder = PushPayload.newBuilder();
		if ("android".equals(platForm)) {// "android"
			builder.setPlatform(Platform.android());
		} else if ("ios".equals(platForm)) {
			builder.setPlatform(Platform.ios());
		} else {
			builder.setPlatform(Platform.all());
		}
		boolean targetAudience = false;
		if (StringHelper.isNotEmpty(aliases)) {
			builder.setAudience(Audience.newBuilder()
					.addAudienceTarget(AudienceTarget.alias(aliases)).build());
			targetAudience = true;
		}

		if (StringHelper.isNotEmpty(tags)) {
			builder.setAudience(Audience.newBuilder()
					.addAudienceTarget(AudienceTarget.tag(tags)).build());
			targetAudience = true;
		}
		if (StringHelper.isNotEmpty(registIds)) {
			builder.setAudience(Audience
					.newBuilder()
					.addAudienceTarget(AudienceTarget.registrationId(registIds))
					.build());
			targetAudience = true;
		}

		if (!targetAudience) {
			builder.setAudience(Audience.all());
		}

		return builder.setNotification(Notification.alert(ALERT)).build();
	}

	/*
	 * 构建推送对象：平台是 Andorid 与 iOS，推送目标是 （"tag1" 与 "tag2" 的并集）且（"alias1" 与 "alias2"
	 * 的并集），推送内容是 - 内容为 MSG_CONTENT 的消息，并且附加字段 from = JPush。
	 */
	public PushPayload buildPushObject_ios_audienceMore_messageWithExtras(
			String MSG_CONTENT) {
		return PushPayload
				.newBuilder()
				.setPlatform(Platform.android_ios())
				.setAudience(
						Audience.newBuilder()
								.addAudienceTarget(
										AudienceTarget.tag("tag1", "tag2"))
								.addAudienceTarget(
										AudienceTarget
												.alias("alias1", "alias2"))
								.build())
				.setMessage(
						Message.newBuilder().setMsgContent(MSG_CONTENT)
								.addExtra("from", "JPush").build()).build();
	}

	/*
	 * 构建推送对象：平台是 iOS，推送目标是 "tag1", "tag_all" 的交集，推送内容同时包括通知与消息 - 通知信息是 ALERT，
	 * 角标数字为 5，通知声音为 "happy"，并且附加字段 from = "JPush"；消息内容是 MSG_CONTENT。通知是 APNs
	 * 推送通道的， 消息是 JPush 应用内消息通道的。APNs 的推送环境是“生产”（如果不显式设置的话，Library 会默认指定为开发）
	 */
	// public PushPayload
	// buildPushObject_ios_tagAnd_alertWithExtrasAndMessage(String ALERT) {
	// return PushPayload
	// .newBuilder()
	// .setPlatform(Platform.ios())
	// .setAudience(Audience.tag_and("tag1", "tag_all"))
	// .setNotification(
	// Notification
	// .newBuilder()
	// .addPlatformNotification(
	// IosNotification.newBuilder()
	// .setAlert(ALERT).setBadge(5)
	// .setSound("happy.caf")
	// .addExtra("from", "JPush")
	// .build()).build())
	// .setMessage(Message.content(MSG_CONTENT))
	// .setOptions(
	// Options.newBuilder().setApnsProduction(true).build())
	// .build();
	// }

}
